from django.contrib.auth import login
from django.shortcuts import render, redirect
from django.views import View
from django.conf import settings, global_settings
from django.http import JsonResponse,HttpResponse

from QQLoginTool.QQtool import OAuthQQ
from carts.utils import merge_carts
import logging
import re


from django_redis import get_redis_connection

from qq.utils import openid_signature,check_openid
from .models import QQUserModel
from meiduo_mall.utils.response_code import RETCODE
from users.models import User

logger = logging.getLogger('django')

# self.client_id = client_id
# self.client_secret = client_secret
# self.redirect_uri = redirect_uri
# self.state = state

# QQ_CLIENT_ID = '101518219'
# QQ_CLIENT_SECRET = '418d84ebdc7241efb79536886ae95224'
# QQ_REDIRECT_URI = 'http://www.meiduo.site:8000/oauth_callback'

class Qqauthorization(View):
    '''qq登陆获取 请求登陆连接路径'''
    def get(self,request):
        # 获取请求路径中的next参数
        request_next = request.GET.get('next')
        oathqq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                         client_secret=settings.QQ_CLIENT_SECRET,
                         redirect_uri=settings.QQ_REDIRECT_URI,
                         state = request_next)
        qq_url = oathqq.get_qq_url()
        return JsonResponse({'login_url':qq_url,'code':RETCODE.OK,'errmsg':'OK'})

class OauthCallback(View):
    '''根据回调地址获取token和openid'''
    def get(self,request):

        code = request.GET.get('code')

        # 对于上面可能出现找不到的结果要记得分类讨论
        if not code:
            return HttpResponse('没有code参数')
        oathqq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                         client_secret=settings.QQ_CLIENT_SECRET,
                         redirect_uri=settings.QQ_REDIRECT_URI
                         )
        try:
            token = oathqq.get_access_token(code)
            openid = oathqq.get_open_id(token)

        # 因qq服务器的回调地址为www.meiduo.site,所以得在四个地方修改地址
        # etc下的hosts，host.js中，dev的host，manage的runserver
        except Exception as e:
            logger.error(e)
            return HttpResponse('请求QQ失败')

        try:
            #  错误的写法 ：user = QQUserModel.objects.get(openid=openid)
            user_model = QQUserModel.objects.get(openid=openid)

        # except:
        except QQUserModel.DoesNotExist:
            # 为了后续能够将用户和openid绑定，这里将openid传到前端的隐藏按钮中，随下次请求发给后端
            # 为了安全起见，这里的openid必须加密保存传给前端
            openid = openid_signature(openid)
            return render(request,'oauth_callback.html',{'openid':openid})
        else:
            next = request.GET.get('next','/')
            #  注意此处不能写直接将user_model传入login()中，状态保持只能用User模型类
            user = user_model.user
            login(request,user)
            response = redirect(next)

            # 购物车未登陆和已登陆合并
            merge_carts(request,response)

            response.set_cookie('username',user,max_age=settings.SESSION_COOKIE_AGE)
            return response

    def post(self,request):
        mobile = request.POST.get('mobile')
        password = request.POST.get('password')
        openid = request.POST.get('openid')
        sms_code = request.POST.get('sms_code')
        next = request.GET.get('state','/')
        if not all([mobile,password]):
            return HttpResponse('缺少参数')
        if not re.match(r'1[345789]\d{9}',mobile):
            return HttpResponse('手机号码错误')
        if not re.match(r'[0-9A-Za-z]{8,20}',password):
            return HttpResponse('密码错误')
        # 校验短信验证码
        if not sms_code:
            return JsonResponse({'code':RETCODE.SMSCODERR,'errmsg':'缺少验证码'})
        redis_conn =get_redis_connection('verify')
        sms_server = redis_conn.get('sms_%s' % mobile)
        if not sms_server:
            return JsonResponse({'code':RETCODE.IMAGECODEERR,'ermsg':'验证码过期'})
        redis_conn.delete('sms_%s' % mobile)
        if sms_code != sms_server.decode():
            return render(request,'oauth_callback.html',{'sms_code_errmsg':'验证码错误'})

        # try:
        #     openid = check_openid(openid)
        # except:
        #     return HttpResponse('openid异常')

        # 对openid解密
        openid = check_openid(openid)
        if not openid:
            return HttpResponse('openid异常')
        try:
            user = User.objects.get(mobile=mobile)
        except:
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            if not user.check_password(password):
                return render(request,'oauth_callback.html',{'account_errmsg':'密码或用户名错误'})
        QQUserModel.objects.create(openid=openid,user=user)
        login(request,user)
        response = redirect(next)
        response.set_cookie('username',user.username,max_age=None)

        # 购物车未登陆和已登陆合并
        merge_carts(request,response)
        return response

